reading-notes

Graphs

A graph is a non-linear data structure that can be looked at as a collection of vertices potentially connected by line segments named edges.

Graph Contents:

Directed vs Undirected

Undirected Graph: An Undirected Graph is a graph where each edge is undirected or bi-directional.

The undirected graph we are looking at has 6 vertices and 7 undirected edges.

Undirected graph visual example:

graph1

Vertices/Nodes = {a,b,c,d,e,f}

Edges = {(a,c),(a,d),(b,c),(b,f),(c,e),(d,e),(e,f)}

Directed Graphs: A Directed Graph also called a Digraph is a graph where every edge is directed.

Direcyed graph visual example:

graph2

Vertices = {a,b,c,d,e,f}

Edges = {(a,c),(b,c),(b,f),(c,e),(d,a),(d,e)(e,c)(e,f)}

Complete vs Connected vs Disconnected

Complete Graphs

A complete graph is when all nodes are connected to all other nodes.

cg

Connected Graphs

A connected graph is graph that has all of vertices/nodes have at least one edge.

cog

Disconnected Graphs

A disconnected graph is a graph where some vertices may not have edges.

graph3

Acyclic vs Cyclic Graphs

Acyclic Graph

An acyclic graph is a directed graph without cycles.

A cycle is when a node can be traversed through and potentially end up back at itself.

Acyclic

Cyclic Graphs

A Cyclic graph is a graph that has cycles.

cyclic

Graph Representation

  1. Adjacency Matrix
  2. Adjacency List

Adjacency Matrix

An Adjacency matrix is represented through a 2-dimensional array. If there are n vertices, then we are looking at an n x n Boolean matrix

adjacent

A few things to note from the above:

Adjacency List

An adjacency list is the most common way to represent graphs.

list

Code Implementation:

Weighted Graphs

A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights.

wg

Traversals

Breadth First

In a breadth first traversal, you are starting at a specific vertex/node. This node must be specified when calling the BreadthFirst() method. The breadth-first traversal of a graph is like that of a tree, with the exception that graphs can have cycles.

Algorithm:

bfs

Pseudo code:

ALGORITHM BreadthFirst(vertex)
    DECLARE nodes <-- new List()
    DECLARE breadth <-- new Queue()
    DECLARE visited <-- new Set()

    breadth.Enqueue(vertex)
    visited.Add(vertex)

    while (breadth is not empty)
        DECLARE front <-- breadth.Dequeue()
        nodes.Add(front)

        for each child in front.Children
            if(child is not visited)
                visited.Add(child)
                breadth.Enqueue(child)   

    return nodes;

Depth First

In a depth first traversal, we approach it a bit different than the way we do when working with a depth first traversal of a tree.

Algorithm:

depth

Graphs Applications

  1. GPS and Mapping
  2. Driving Directions
  3. Social Networks
  4. Airline Traffic
  5. Netflix uses graphs for suggestions of products